/**
 * Notes: 表白墙发布页面 (新版API)
 * Ver : WeCollege Server API 1.0.0
 * Date: 2025-01-27
 * Description: 使用新的API服务重构表白墙发布功能
 */

const pageHelper = require('../../../../../helper/page_helper.js');
const BoardBiz = require('../../../biz/board_biz_new.js');
const validate = require('../../../../../helper/validate.js');
const PublicBiz = require('../../../../../comm/biz/public_biz.js');
const ProjectBiz = require('../../../biz/project_biz.js');
const PassportBiz = require('../../../../../comm/biz/passport_biz.js');
const { UploadService } = require('../../../../../helper/api_services.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isLoad: false,
    
    // 表单数据
    formTitle: '',
    formContent: '',
    formTo: '',
    formFrom: '',
    formDesc: '',
    formCateId: 'love',
    
    // 图片数据
    formPic1: '',
    formPic2: '',
    formPic3: '',
    
    // 分类选项
    cateOptions: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    ProjectBiz.initPage(this);

    // 检查登录状态
    if (!await PassportBiz.loginMustBackWin(this)) return;

    // 初始化数据
    this.setData({
      ...BoardBiz.initFormData(),
      cateOptions: BoardBiz.getCateList(),
      isLoad: true
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () { },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () { },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () { },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () { },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: async function () { 
    wx.stopPullDownRefresh();
  },

  /**
   * 页面跳转
   */
  url: function (e) {
    pageHelper.url(e, this);
  },

  /**
   * 输入框变化事件
   */
  bindInputChange: function (e) {
    const { field } = pageHelper.dataset(e);
    const { value } = e.detail;
    this.setData({
      [field]: value
    });
  },

  /**
   * 分类选择事件
   */
  bindCateChange: function (e) {
    const { value } = e.detail;
    const cateOptions = this.data.cateOptions;
    this.setData({
      formCateId: cateOptions[value].value
    });
  },

  /**
   * 图片选择事件
   */
  bindChooseImage: function (e) {
    const { field } = pageHelper.dataset(e);
    const that = this;
    
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        const tempFilePath = res.tempFilePaths[0];
        that.setData({
          [field]: tempFilePath
        });
      }
    });
  },

  /**
   * 删除图片事件
   */
  bindDeleteImage: function (e) {
    const { field } = pageHelper.dataset(e);
    this.setData({
      [field]: ''
    });
  },

  /**
   * 预览图片事件
   */
  bindPreviewImage: function (e) {
    const { url } = pageHelper.dataset(e);
    const urls = [this.data.formPic1, this.data.formPic2, this.data.formPic3]
      .filter(pic => pic);
    
    wx.previewImage({
      current: url,
      urls: urls
    });
  },

  /**
   * 表单提交事件
   */
  bindFormSubmit: async function () {
    // 检查登录状态
    if (!await PassportBiz.loginMustCancelWin(this)) return;

    // 获取表单数据
    let data = {
      formTitle: this.data.formTitle,
      formContent: this.data.formContent,
      formTo: this.data.formTo,
      formFrom: this.data.formFrom,
      formDesc: this.data.formDesc,
      formCateId: this.data.formCateId,
      formPic1: this.data.formPic1,
      formPic2: this.data.formPic2,
      formPic3: this.data.formPic3,
    };

    // 表单验证
    data = validate.check(data, BoardBiz.CHECK_FORM, this);
    if (!data) return;

    // 设置分类名称
    data.cateName = BoardBiz.getCateName(data.formCateId);

    try {
      wx.showLoading({ title: '发布中...', mask: true });

      // 上传图片
      await this._uploadImages(data);

      // 发布表白墙
      const result = await BoardBiz.insert(data);
      const boardId = result.data.id;

      wx.hideLoading();

      // 成功回调
      const callback = async function () {
        // 清除缓存
        PublicBiz.removeCacheList('admin-board-list');
        PublicBiz.removeCacheList('board-list');
        
        // 返回上一页
        wx.navigateBack();
      };

      pageHelper.showSuccToast('发表成功', 2000, callback);

    } catch (err) {
      wx.hideLoading();
      console.error('发布失败:', err);
      
      wx.showModal({
        title: '发布失败',
        content: err.message || '网络异常，请稍后重试',
        showCancel: false
      });
    }
  },

  /**
   * 上传图片
   * @param {object} data - 表单数据
   */
  async _uploadImages(data) {
    const imageFields = ['formPic1', 'formPic2', 'formPic3'];
    
    for (const field of imageFields) {
      const imagePath = data[field];
      if (imagePath && this._isTempFile(imagePath)) {
        try {
          // 这里需要根据实际的上传接口调整
          // 暂时保持原有路径，实际项目中需要上传到服务器
          console.log(`需要上传图片: ${field} = ${imagePath}`);
          // const uploadResult = await UploadService.image(imagePath);
          // data[field] = uploadResult.data.url;
        } catch (uploadErr) {
          console.error(`图片上传失败 ${field}:`, uploadErr);
          // 上传失败时保持原路径或清空
          // data[field] = '';
        }
      }
    }
  },

  /**
   * 判断是否为临时文件
   * @param {string} filePath - 文件路径
   * @returns {boolean} 是否为临时文件
   */
  _isTempFile(filePath) {
    return filePath && (
      filePath.includes('tmp') || 
      filePath.includes('temp') || 
      filePath.includes('wxfile')
    );
  }

});